package com.dsteiner.widgets.client;

import java.util.ArrayList;
import java.util.List;

import com.dsteiner.widgets.client.Widgets.IListBox;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;

public class ListBoxWidget extends ListBox implements ChangeListener, IListBox{

	private String selectedItem;

	public ListBoxWidget(boolean multiSelect) {
		super(multiSelect);
		addChangeListener(this);
	}
	
	public ListBoxWidget() {
		this(false);
	}
	
	public String getSelectedItem() {
		int selectedIndex = getSelectedIndex();
		String selectedItem = null;
		if(selectedIndex != -1 && selectedIndex < getItemCount())
			selectedItem = getItemText(selectedIndex);
		return selectedItem;
	}

	public void onChange(Widget arg0) {
		setSelectedItem(getValue(getSelectedIndex()));
	}

	public void setItems(List<String> items, List<String> values) {
		clear();
		addItems(items, values);
		setSelectedItem(selectedItem);
	}

	public void addItems(List<String> items, List<String> values) {
		if(items == null)
			return;
		for (int i = 0; i < items.size(); i++) {
			addItem(items.get(i), values.get(i));
		}
	}

	public void setItems(List<String> items) {
		List<String> values = new ArrayList<String>();
		if(items == null)
			items = new ArrayList<String>();
		values.addAll(items);
		setItems(items, values);
	}

	public void setSelectedItems(List<String> list) {
		setSelectedIndex(-1);
		if(list == null)
			return;
		for (String selectedItem : list) {
			setSelectedItem(selectedItem);
		}
	}

	
	public void setSelectedItem(String selectedItem) {
		this.selectedItem = selectedItem;
		for (int i = 0; i < getItemCount(); i++) {
			String item = getItemText(i);
			String value = getValue(i);
			if(value != null && value.equals(selectedItem) || item.equals(selectedItem)){
				setItemSelected(i, true);
				return;
			}
		}
	}

	public String getSelectedValue() {
		int selectedIndex = getSelectedIndex();
		return selectedIndex >= 0 && selectedIndex < getItemCount() ? getValue(selectedIndex) : null;
	}

}
